package com.aspsine.multithreaddownload.demo.util;

import com.aspsine.multithreaddownload.App;
import com.aspsine.multithreaddownload.util.ListUtils;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.bundle.BundleInfo;
import ohos.bundle.IBundleManager;
import ohos.rpc.RemoteException;
import ohos.utils.net.Uri;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;

import static ohos.aafwk.content.Intent.ACTION_PLAY;

/**
 * Created by Aspsine on 2015/7/29.
 */
public class Utils {

    public static final File mDownloadDir = new
            File(App.getGlobalContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),"Download");

    private static final DecimalFormat DF = new DecimalFormat("0.00");

    public static String getDownloadPerSize(long finished, long total) {
        return DF.format((float) finished / (1024 * 1024)) + "M/" +
                DF.format((float) total / (1024 * 1024)) + "M";
    }

    public static void installApp(Context context, File file) {
//        Intent intent = new Intent(Intent.ACTION_VIEW);
        Intent intent = new Intent();
       // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setFlags(Intent.FLAG_ABILITY_NEW_MISSION);
        intent.setUriAndType(Uri.getUriFromFile(file),ACTION_PLAY);
//        context.startActivity(intent);
        context.startAbility(intent,0);
    }

    public static void unInstallApp(Context context, String packageName) {
        Uri packageUri = Uri.parse("package:" + packageName);
//        Intent intent = new Intent(Intent.ACTION_DELETE, packageUri);
        Intent intent = new Intent();
        intent.setUriAndType(packageUri,Intent.ACTION_QUERY_TRAVELLING_GUIDELINE);
        intent.setFlags(Intent.FLAG_ABILITY_NEW_MISSION);
        context.startAbility(intent,0);
    }

    public static String getApkFilePackage(Context context, File apkFile) {

        IBundleManager pm = context.getBundleManager();
        BundleInfo info = pm.getBundleArchiveInfo(apkFile.getPath(),
                IBundleManager.GET_BUNDLE_WITH_ABILITIES);
        if (info != null){
            return info.appInfo.name;
        }
        return null;
    }

    public static boolean isAppInstalled(Context context,String packageName) {
        List<BundleInfo> packages = null;
        try {
            packages = context.getBundleManager().getBundleInfos(0);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        if (!ListUtils.isEmpty(packages)) {
            for (BundleInfo packageInfo : packages) {
                if (packageInfo.appInfo.name.equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }
}
